package org.mozhu.mboot.core.web;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Set;

@Slf4j
public class PerformanceListener implements ServletRequestListener {

    private HttpServletRequestSkipper httpServletRequestSkipper;

    public PerformanceListener(Set<String> exclusions) {
        httpServletRequestSkipper = new HttpServletRequestSkipper(exclusions);
    }

    public PerformanceListener(Set<String> exclusions, Set<String> inclusions) {
        httpServletRequestSkipper = new HttpServletRequestSkipper(exclusions, inclusions);
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        ServletRequest servletRequest = sre.getServletRequest();
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        Long startTime = (Long) (httpServletRequest.getAttribute("startTime"));
        if (startTime != null) {
            String requestURI = httpServletRequest.getRequestURI();
            String method = httpServletRequest.getMethod();
            long endTime = System.currentTimeMillis();
            long costTime = endTime - startTime;
            log.info("Performance of URI [{}][{}]: StartTime[{}], EndTime[{}], CostTime[{}]", method, requestURI, startTime, endTime, costTime);
            httpServletRequest.setAttribute("endTime", endTime);
            httpServletRequest.setAttribute("costTime", costTime);
        }

    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        ServletRequest servletRequest = sre.getServletRequest();
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        if (httpServletRequestSkipper.needSkip(httpServletRequest)) {
            return;
        }
        long startTime = (new Date()).getTime();
        sre.getServletRequest().setAttribute("startTime", startTime);
    }
}